<?php

/**
 * ApplicationConfigBehavior is a behavior for the application.
 * It loads additional config parameters that cannot be statically 
 * written in config/main
 */
class ApplicationConfigBehavior extends CBehavior {

    /**
     * Declares events and the event handler methods
     * See yii documentation on behavior
     */
    private $_csrfToken;

    public function events() {
        return array_merge(parent::events(), array(
            'onBeginRequest' => 'beginRequest',
        ));
    }

    /**
     * Load configuration that cannot be put in config/main
     */
    public function beginRequest() {
        if (isset($_POST['lang']))
            $this->owner->user->setState('applicationLanguage', $_POST['lang']);
        if ($this->owner->user->getState('applicationLanguage'))
            $this->owner->language = $this->owner->user->getState('applicationLanguage');
        else
            $this->owner->language = 'en';
    }

//    public function getCsrfToken() {
//        if ($this->_csrfToken === null) {
//            $session = Yii::app()->session;
//            $csrfToken = $session->itemAt($this->csrfTokenName);
//            if ($csrfToken === null) {
//                $csrfToken = sha1(uniqid(mt_rand(), true));
//                $session->add($this->csrfTokenName, $csrfToken);
//            }
//            $this->_csrfToken = $csrfToken;
//        }
//
//        return $this->_csrfToken;
//    }
//
//    public function validateCsrfToken($event) {
//        if ($this->getIsPostRequest()) {
//            // only validate POST requests
//            $session = Yii::app()->session;
//            if ($session->contains($this->csrfTokenName) && isset($_POST[$this->csrfTokenName])) {
//                $tokenFromSession = $session->itemAt($this->csrfTokenName);
//                $tokenFromPost = $_POST[$this->csrfTokenName];
//                $valid = $tokenFromSession === $tokenFromPost;
//            } else
//                $valid = false;
//            if (!$valid)
//                throw new CHttpException(400, Yii::t('yii', 'The CSRF token could not be verified.'));
//        }
//    }

}
